package com.pzr.soccer.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pzr.soccer.model.RT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;

import com.alibaba.fastjson.JSON;
import com.pzr.soccer.constans.Consts;
import com.pzr.soccer.model.R;

import lombok.extern.slf4j.Slf4j;

@Order(0)
@WebFilter(servletNames = "userCheckTokenFilter",urlPatterns = "/*")
@Slf4j
public class UserCheckTokenFilter implements Filter {
	@Value("${allow.noToken.access.url:/soccer/login,/soccer/logout,/soccer/registry," +
			"/soccer/validation/**,/soccer/setPasswordByPhone,/soccer/setPasswordByEmail,/soccer/fetchUsernameByPhone,/soccer/fetchUsernameByEmail" +
			"/test/**}")
	private Set<String> allowNoTokenAccessUrls;
	@Autowired
	RedisTemplate<String, Object> redisTemplate;


	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpReq=(HttpServletRequest) request;
		String remoteUser = httpReq.getRemoteUser();
		String requestedSessionId = httpReq.getRequestedSessionId();
		log.info(String.format("remoteUser:%s,sessionId:%s",remoteUser,requestedSessionId));
		String path=httpReq.getRequestURI();
		System.out.println("requesting  "+path);
		if(allowNoTokenAccessUrls.contains(path)) {
			log.info("this url don't need token");
			chain.doFilter(request, response);
			return;
		}
		
		String token=httpReq.getHeader(HttpHeaders.AUTHORIZATION);
		
		if(redisTemplate.hasKey(Consts.Redis_Token_Black_List_Prefix+token)) {
			log.info("invalid or expired token");
			flushUnauthorizedResult(response);
			return;
		}

		chain.doFilter(request,response);
		
	}
	
    private void flushUnauthorizedResult(ServletResponse response) {
        HttpServletResponse httpRes=(HttpServletResponse) response;
        response.setContentType("application/json;charset=utf-8");
        R<Object> r=R.fail("token过期或者无效", RT.s(RT.Security_Tag_Authentication));
        try {
			PrintWriter writer = httpRes.getWriter();
			//httpRes.setStatus(401);
			writer.write(JSON.toJSONString(r));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
     
    }


}
